import { ref } from "vue";
import {
  getArticleApi,
  getArticleByIdApi,
} from "../api/article_api";
import { getTimeYMDHMS } from "../utils/time";
import { useCode } from "./codeHook.ts";
import type { articleData } from "../utils/interface";
const { tackleCode } = useCode();


export function useArticle() {
  // 文章ID，用于编辑文章时传递给后端
  const id = ref<number>();
  //收取cover封面
  const cover = ref();
  const coverData = (e: any) => {
    cover.value = e;
  };

  //文章列表
  const articleList = ref<articleData[]>([]);
  //文章总数
  const articlCount = ref<number>(0);
  const catArtCount = ref<number>(0);
  //获取文章
  const getArticle = (request: any) => {
    try {
      getArticleApi(request).then((res) => {
        if (tackleCode(res.data.code)) {
          articleList.value = []; // 清空文章列表
          articlCount.value = 0; // 重置文章总数
          const data = res.data.data;
          articlCount.value = data.count; // 更新文章总数
          articleList.value = [...data.result]; // 更新文章列表
          catArtCount.value = data.result.length;
        }
      });
    } catch (error) {
      console.error("获取文章失败", error);
    }
  };

  //获取文章详情
  const defaultArticle = ref();
  const getArticleById = (e: number) => {
    let request = {
      id: e, // 文章id
    };
    id.value = e;
    getArticleByIdApi(request).then((res: any) => {
      if (tackleCode(res.data.code)) {
        // 获取文章详情数据
        defaultArticle.value = res.data.data;
        // 处理时间格式
        defaultArticle.value.created_at = getTimeYMDHMS(
          new Date(defaultArticle.value.created_at)
        );
      }
    });
  };

  return {
    getArticle,
    articleList,
    articlCount,
    catArtCount,
    getArticleById,
    defaultArticle,
    coverData,
  };
}